jsPlumb.ready(function () {
    var data = {
        "title":"工作流数据"
    };
    var lines = {},
        nodes = {},
        index = 0;
    // 设置默认对象为jsPlumb
    var instance = jsPlumb.getInstance({
        Endpoint: ["Dot", {radius: 2}], //点的类型
        Connector:"Straight", //线的类型
        HoverPaintStyle: {stroke: "#1e8151", strokeWidth: 2 },//hover样式
        ConnectionOverlays: [  //箭头处的类型
            [ "Arrow", {
                location: 1,//arrow 与初始点的位置
                id: "arrow", //arrow id
                length: 14, //arrow 尺寸大小
                foldback: 0.8 //箭头粗细度 值越小 arrow边缘越小      
            }],
            //[ "Label", { label: "", id: "label", cssClass: "aLabel" }] //线上面的标记盒子
             [ "Label", {
                location: 0.5,
                id: "label",
                cssClass: "aLabel",
                events:{
                    tap:function(e) { 
                        //console.log("hi");
                    }
                }
            }]
        ],
        Container: "topDiv" //必须为id
    });
    //anchor有四种类型：
    // static：固定不可移动的点
    // dynamic：从一组staticanchor中，每次动态选取一个合适的
    // perimeter：沿着特定图形的边
    // continous：没有固定的位置，根据线另一端点的朝向决定
    instance.registerConnectionType("basic", { anchor:"Continuous", connector:"Straight" }); //改变线的类型时这个一定要改
    window.jsp = instance;
    // 点击连线删除
     instance.bind("click", function (c,e) {
         if($(e.target).attr("class") == "deleteIcon"){
            if (confirm("确定删除吗?")) {
                instance.deleteConnection(c);
            }
         }else if($(e.target).attr("class") == "editIcon"){
             showData(c, 0); // 0为线 1为div
            $(".hideBtn").trigger("click");
        } 
    });
    instance.bind("connection", function (info) { //划线停止后mouseUp触发事件
        info.connection.getOverlay("label").setLabel(function(){
            var iconDiv = '<div class="iconDiv">\
                            <span class="editIcon"></span>\
                            <span class="deleteIcon"></span>\
                            <em class="lineN">'+info.connection.id+'</em>\
                        </div>';
            return iconDiv;
        });
    });
    // 创建node 设置起始点，目标点.
    var initNode = function(el) {
        instance.draggable(el,{containment: "parent"}); //限制拖动不超过父级边框
        instance.makeSource(el, {
            filter: ".ep",
            anchor: "Continuous",
            connectorStyle: { stroke: "#5c96bc", strokeWidth: 2, outlineStroke: "transparent", outlineWidth: 4 },
            connectionType:"basic",
            extract:{
                "action":"the-action"
            },
            maxConnections: -1,
            onMaxConnections: function (info, e) { //最大连接数
               // alert("Maximum connections (" + info.maxConnections + ") reached");
            }
        });
        instance.makeTarget(el, { //连线箭头指向的终点位置，如果注销，连接失败
            dropOptions: { hoverClass: "dragHover" },
            anchor: "Continuous",
            allowLoopback: false,//自己连自己
        });
        instance.fire("jsPlumbDemoNodeAdded", el);
    };
    //dom操作
    var getNodes = function(){
        $(".topDiv .item").each(function(){
            nodes["node_" + $(this).attr("id")] = {
                name:$(this).attr("data-name"),
                left:parseInt($(this).css("left")),
                top:parseInt($(this).css("top")),
                width:$(this).width(),
                height:$(this).height()
            };
        });
        return nodes;
    };
    var getLines = function(allLines){
        var lineName;
        for(var i in allLines){
            lineName = $("#"+allLines[i].getOverlay("label").canvas.id).find(".lineN").html();
            lines["line_" + allLines[i].id] = {
                "lineid":allLines[i].id,
                "name":lineName,
                "from":allLines[i].sourceId,
                "to":allLines[i].targetId
            };
        }
        return lines;
    };
    var showData = function(c, num){
        $(".conts .cont").eq(num).show().siblings(".cont").hide();
        if(num == 0){
            $(".svgForm").find(".lineName").val(c.id).attr("oldId", c.id);
        }else{
            $(".conts .cont").eq(num).show().siblings(".cont").hide();
            $(".divForm input").eq(0).val(c.name).attr("oldId", c.id);
            $(".divForm input").eq(1).val(c.text);
        }
    };
    var operation = function(){
        //setStyle center
        $(".downDiv").css({height:$(".itemRight").height() - $(".topDiv").height() -14 + "px"});
        $(window).resize(function(){
            $(".downDiv").css({height:$(".itemRight").height() - $(".topDiv").height() -14 + "px"});
        });
        //rightDiv btn
        $(".hideBtn").on("click",function(c){ 
            if(index == 0){
                $(".rightDiv").animate({right:0},500,function(){});
                index++;
             }else{
                $(".rightDiv").animate({right:-($(".rightDiv").outerWidth(true) + 10) + "px"},500,function(){});
                index--;
             }
        });
        //right arrow and rightDiv btn
        $(".arrowBtn,.save").on("click",function(){
            $(".rightDiv").animate({right:-($(".rightDiv").outerWidth(true) + 10) +"px"},500,function(){
                index = 0;
            });
        });
        $(".save").on("click",function(){
            if($(".cont2").is(":visible")){ //div
                var newData = {};
                newData = {
                    oldId:$(".cont2").find("input").eq(0).attr("oldId"),
                    name:$(".cont2").find("input").eq(0).val(),
                    text:$(".cont2").find("input").eq(1).val()
                };
                $(".topDiv .item").each(function(){
                    if(newData.oldId == $(this).attr("id")){
                         $(this).attr("data-name", newData.name);
                         $(this).find(".text").text(newData.text);
                    }                     
                 });   
            }else{
                var newLineName = $(".lineName").val(),
                    oldLineId = $(".lineName").attr("oldId");
                var allLines = instance.getAllConnections();
                for(var index in allLines){
                    if(allLines[index].id == oldLineId){
                        $("#"+allLines[index].getOverlay("label").canvas.id).find(".lineN").html(newLineName)
                    }
                }
            }
        });
        $(document).on("mouseenter", ".topDiv .item", function () {
            var ele=$('<span>X</span>');
            ele.css({
                position:"absolute",
                left:"154px",
                top:"0",
                width:16+"px",
                height:16+"px",
                textAlign:"center",
                lineHeight:16+"px",
                cursor:"pointer"
            });
            $(this).append(ele);
        }).on("mouseleave", ".topDiv .item", function () {
            $(this).find("span").remove();
        }).on("dblclick",".topDiv .item", function(){
            var nodeData = {
                    id:$(this).attr("id"),
                    name:$(this).attr("data-name"),
                    text:$(this).find(".text").text()
                };
            $(".rightDiv").animate({right:0 +"px"},500,function(){
                showData(nodeData,1);
                index = 0;
            });
        }).on("click", ".topDiv .item span",function () {
            if (confirm("确定删除吗?")) {
                var allLines = instance.getAllConnections($(this).parent().attr("id"));
                instance.removeAllEndpoints($(this).parent().attr("id")); //删除dom上所有点 官网detachAllConnections(el,[params]) 不好使
                $(this).parent().remove();
            }
        });
        //save date
        $(".saveData").on("click",function(){
            lines = {};
            nodes = {};
            var allLines = instance.getAllConnections();
            if(allLines.length != 0){
                data.lines = getLines(allLines);
            }else{
                data.lines = lines = {};
            }
            data.nodes = getNodes();
            data.initNum =  (Object.keys(data.lines).length + Object.keys(data.nodes).length);
            console.log(data);
        });
    };
    // 暂停绘图并初始化.
    instance.batch(function () {
        var data = [
            {
                "id":"No1",
                "text":1111111
            },
            {
                "id":"No2",
                "text":222222
            }
        ];
        for (var i = 0; i < data.length; i++) {
            var item = '<div class="item" data-name ="' 
                            + data[i].text + '" data-id="'
                            + data[i].id + '">' + data[i].text +
                        '</div>';
                $(".itemLeft").append(item); 
        }
        $(document).find(".itemLeft .item").draggable({ //元素标签可拖拽
            helper: "clone",
            stop: function(e,ui){
                var left = parseInt(ui.offset.left - $(".topDiv").offset().left);
                var top = parseInt(ui.offset.top - $(".topDiv").offset().top);
                var ele=$('<div class="item" data-name="'+ $(ui.helper).attr("data-name") +'" data-id="' + $(ui.helper).attr("data-id") + '" >' +
                    '<div class="text">'+$(ui.helper).html()+'</div>\
                    <div class="ep ep1"></div>\
                    <div class="ep ep2"></div>\
                    <div class="ep ep3"></div>\
                    <div class="ep ep4"></div>\
                </div>');//$(ui.helper).html()取第一个JQ元素的文本
                if(ui.offset.left >= $(".topDiv").offset().left){ //是否到拖放区域
                    ele.css({
                        "left":left,
                        "top":top,
                        position: "absolute",
                        margin:0
                    });
                    $(".topDiv").append(ele);
                    initNode(ele); 
                }else{
                    ele.remove();
                }
                jsPlumb.repaintEverything();
            }
        });
         
    });
    jsPlumb.fire("jsPlumbDemoLoaded", instance);
    operation();
});